<template>
  <div class="home-container">
    <!-- 欢迎页面 -->
    <div class="welcome-section">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card clickable" @click="goToTemplates">
          <div class="stat-icon">
            <i class="el-icon-folder"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statsData.templateCount }}</h3>
            <p>模板总数</p>
            <span class="click-hint">点击查看详情</span>
          </div>
        </div>

        <div class="stat-card clickable" @click="goToPages">
          <div class="stat-icon">
            <i class="el-icon-document"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statsData.pageCount }}</h3>
            <p>页面总数</p>
            <span class="click-hint">点击查看详情</span>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statsData.userCount }}</h3>
            <p>活跃用户</p>
          </div>
        </div>

        <!-- <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-time"></i>
          </div>
          <div class="stat-content">
            <h3>{{ statsData.todayCount }}</h3>
            <p>今日新增</p>
          </div>
        </div> -->
      </div>
    </div>

    <!-- 统计图表 -->
    <div class="chart-section">
      <div class="chart-header">
        <!-- <h2>数据统计图表</h2> -->
        <div class="chart-controls">
          <el-radio-group v-model="chartType" @change="updateChartData">
            <el-radio-button label="total">总数</el-radio-button>
            <el-radio-button label="today">今日新增</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container">
        <v-chart class="stats-chart" :option="chartOption" :autoresize="true" />
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts/core";
import { BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
]);

export default {
  name: "Home",
  data() {
    return {
      recentPages: [],
      statsData: {
        templateCount: 0,
        pageCount: 0,
        userCount: 0,
        todayCount: 0,
      },
      userStats: {
        myTemplates: 0,
        myPages: 0,
        lastActive: "未知",
      },
      chartType: "total", // 图表类型：total-总数，today-今日新增
      chartOption: {
        title: {
          text: "系统数据概览",
          left: "center",
          textStyle: {
            color: "#2c3e50",
            fontSize: 18,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: ["模板数", "页面数", "用户数"],
          top: 40,
        },
        xAxis: {
          type: "category",
          data: ["模板数", "页面数", "用户数"],
          axisLabel: {
            color: "#666",
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#666",
          },
        },
        series: [
          {
            name: "数据统计",
            type: "bar",
            data: [0, 0, 0],
            itemStyle: {
              color: function (params) {
                const colors = ["#667eea", "#f093fb", "#4facfe"];
                return colors[params.dataIndex];
              },
            },
            label: {
              show: true,
              position: "top",
              color: "#2c3e50",
              fontSize: 14,
              fontWeight: "bold",
              formatter: "{c}",
            },
          },
        ],
      },
    };
  },
  async created() {
    await this.loadStats();
    await this.loadUserStats();
    await this.loadRecentPages();
  },
  methods: {
    // 加载统计数据
    async loadStats() {
      try {
        const { getSystemStats } = await import("@/api");
        const stats = await getSystemStats();

        this.statsData = {
          templateCount: stats.templateCount,
          pageCount: stats.pageCount,
          userCount: stats.userCount,
          todayCount: stats.todayCount,
        };

        // 更新图表数据
        this.updateChartData();
      } catch (error) {
        console.error("加载统计数据失败:", error);
      }
    },

    // 更新图表数据
    updateChartData() {
      let chartData;
      let chartTitle;

      if (this.chartType === "total") {
        // 显示总数
        chartData = [
          this.statsData.templateCount,
          this.statsData.pageCount,
          this.statsData.userCount,
        ];
        chartTitle = "系统数据总数";
      } else {
        // 显示今日新增
        const today = new Date().toDateString();
        const templates = JSON.parse(
          localStorage.getItem("vform-templates") || "[]"
        );
        const pages = JSON.parse(
          localStorage.getItem("vform-generated-pages") || "[]"
        );

        const todayTemplates = templates.filter((t) => {
          const createDate = new Date(t.createTime).toDateString();
          return createDate === today;
        });

        const todayPages = pages.filter((p) => {
          const createDate = new Date(p.createTime).toDateString();
          return createDate === today;
        });

        chartData = [todayTemplates.length, todayPages.length, 0]; // 用户数今日新增为0
        chartTitle = "今日新增数据";
      }

      // 更新图表配置
      this.chartOption = {
        ...this.chartOption,
        title: {
          ...this.chartOption.title,
          text: chartTitle,
        },
        series: [
          {
            name: "数据统计",
            type: "bar",
            data: chartData,
            itemStyle: {
              color: function (params) {
                const colors = ["#667eea", "#f093fb", "#4facfe"];
                return colors[params.dataIndex];
              },
            },
            label: {
              show: true,
              position: "top",
              color: "#2c3e50",
              fontSize: 14,
              fontWeight: "bold",
              formatter: "{c}",
            },
          },
        ],
      };
    },

    // 加载用户统计
    async loadUserStats() {
      try {
        const { getUserStats } = await import("@/api");
        const userStats = await getUserStats();

        this.userStats = {
          myTemplates: userStats.myTemplates,
          myPages: userStats.myPages,
          lastActive: userStats.lastActive,
        };
      } catch (error) {
        console.error("加载用户统计失败:", error);
      }
    },

    // 获取当前用户
    getCurrentUser() {
      const userInfo = localStorage.getItem("current-user");
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo);
          return user.name || user.username || "系统用户";
        } catch (error) {
          console.error("解析用户信息失败:", error);
        }
      }
      return "系统用户";
    },

    // 加载最近生成的项目
    async loadRecentPages() {
      try {
        const { getPages } = await import("@/api");
        const pageList = await getPages();
        // 取最近5个
        this.recentPages = pageList.slice(0, 5);
      } catch (error) {
        console.error("加载最近项目失败:", error);
      }
    },

    // 跳转到设计器
    goToDesigner() {
      this.$router.push("/designer");
    },

    // 跳转到模板管理
    goToTemplates() {
      this.$router.push("/templates");
    },

    // 跳转到页面管理
    goToPages() {
      this.$router.push("/pages");
    },

    // 跳转到表单渲染
    goToRender() {
      this.$router.push("/render");
    },

    // 跳转到表单预览
    goToPreview() {
      this.$router.push("/preview");
    },

    // 打开项目
    openProject(page) {
      this.$router.push(`/page/${page.routeName}`);
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN");
    },
  },
};
</script>

<style scoped>
.home-container {
  min-height: calc(100vh - 40px);
  background: #f5f5f5;
  padding: 0;
}

.welcome-section {
  text-align: center;
  margin-bottom: 20px;
}

.welcome-title {
  color: #2c3e50;
  font-size: 36px;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.welcome-desc {
  color: #7f8c8d;
  font-size: 18px;
  margin: 0 0 50px 0;
}

.stats-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
  align-items: stretch;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  min-width: 200px;
  flex: 0 0 auto;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-card.clickable {
  cursor: pointer;
}

.stat-card.clickable:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card:nth-child(1) .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card:nth-child(2) .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card:nth-child(3) .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card:nth-child(4) .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content h3 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.stat-content p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.click-hint {
  font-size: 12px;
  color: #409eff;
  opacity: 0;
  transition: opacity 0.3s ease;
  margin-top: 5px;
  display: block;
}

.stat-card.clickable:hover .click-hint {
  opacity: 1;
}

.quick-actions {
  background: white;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quick-actions h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 30px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.user-stats {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.user-stats h2 {
  color: #2c3e50;
  font-size: 24px;
  margin: 0 0 30px 0;
}

.user-stats-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.user-stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.user-stat-item:hover {
  border-color: #409eff;
  background: #f0f8ff;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
}

.chart-section {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-section h2 {
  color: #2c3e50;
  font-size: 24px;
  margin: 0;
}

.chart-controls {
  display: flex;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.stats-chart {
  width: 100%;
  height: 100%;
}

.recent-projects {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.recent-projects h2 {
  color: #2c3e50;
  font-size: 24px;
  margin: 0 0 30px 0;
}

.project-list {
  display: grid;
  gap: 20px;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border-left: 4px solid #409eff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.project-item:hover {
  background: #e9ecef;
  transform: translateX(5px);
}

.project-info h4 {
  color: #2c3e50;
  font-size: 18px;
  margin: 0 0 8px 0;
}

.project-info p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.project-date {
  color: #95a5a6;
  font-size: 12px;
}

.project-actions {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .home-container {
    padding: 20px 10px;
  }

  .welcome-title {
    font-size: 32px;
  }

  .welcome-desc {
    font-size: 16px;
  }

  .feature-cards {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .stats-cards {
    gap: 15px;
  }

  .stat-card {
    padding: 15px;
    min-width: 180px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }

  .stat-content h3 {
    font-size: 24px;
  }

  .chart-container {
    height: 300px;
  }

  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .chart-section h2 {
    font-size: 20px;
  }

  .user-stats-content {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .project-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    flex-direction: column;
    align-items: stretch;
  }

  .stat-card {
    padding: 15px;
    min-width: auto;
    width: 100%;
  }

  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
    margin-right: 12px;
  }

  .stat-content h3 {
    font-size: 20px;
  }

  .chart-container {
    height: 250px;
  }

  .chart-section {
    padding: 20px;
  }

  .chart-header {
    flex-direction: column;
    align-items: stretch;
  }

  .chart-controls {
    justify-content: center;
  }
}
</style>
